import uuid

import pymysql
from pymysql import Error


# 复制一码通用户角色数据
def copy_role_permissions():
    # 数据库连接配置
    source_db_config = {
        'host': '10.1.213.159',
        'user': 'GTXS_user',
        'password': 'GTXS_user_JG123',
        'database': 'sysmandb',
        'charset': 'utf8mb4'
    }

    target_db_config = {
        'host': '10.99.81.155',
        'port': 8306,
        'user': 'jg_usercenter',
        'password': 'Jg_usercenter_20250312',
        'database': 'jg_usercenter',
        'charset': 'utf8mb4'
    }

    try:
        # 连接源数据库和目标数据库
        source_conn = pymysql.connect(**source_db_config)
        target_conn = pymysql.connect(**target_db_config)

        with source_conn.cursor() as source_cursor, target_conn.cursor() as target_cursor:
            # 从源数据库获取所有角色权限数据
            source_cursor.execute("SELECT guid, sys_role_id as role_id, sys_user_id as user_id, "
                                  "create_user, create_date, change_user, change_date FROM sys_user_role "
                                  "ORDER BY sys_role_id ")
            source_data = source_cursor.fetchall()

            # 从目标数据库获取现有角色权限数据
            # target_cursor.execute("SELECT role_id, user_id, id FROM sys_user_role")
            # target_data = target_cursor.fetchall()

            # 创建目标数据的字典，方便查找
            # target_dict = {(row[0], row[1]): row[2] for row in target_data}

            count = 0
            # 遍历源数据
            for source_row in source_data:
                # 获取目标库中的ID
                source_id = str(uuid.uuid4())
                role_id = str(source_row[1])
                user_id = source_row[2]

                if role_id.startswith('51'):
                    role_id = role_id.replace(role_id[:2], '52')
                else:
                    role_id = '52' + role_id

                # 插入新记录
                insert_query = """
                INSERT INTO sys_user_role (id, role_id, user_id, tenant_id, remark, 
                    create_user, create_date, change_user, change_date) 
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
                """
                target_cursor.execute(insert_query, (source_id, role_id, user_id, '010', 'copy for ymt role',
                                                     source_row[3], source_row[4], source_row[5], source_row[6]))

                count += 1
                print(count)

            # 提交事务
            target_conn.commit()

            print(f"同步完成！总计: {count} 条记录")
            print("角色权限数据同步完成")

    except Error as e:
        print(f"数据库操作出错: {e}")
        # 回滚事务
        if 'target_conn' in locals():
            target_conn.rollback()
    finally:
        # 关闭数据库连接
        if 'source_conn' in locals():
            source_conn.close()
        if 'target_conn' in locals():
            target_conn.close()


if __name__ == "__main__":
    copy_role_permissions()
